const ProductItemType = {
    spu: String, // 商品的spu
    title: String, //标题
    model_img: Array, // 模特列表
    design_list: Array, //设计面信息
    source: String, //商品来源
    design_id: Number, // 如果来源是设计的模板，则有设计id
    color_base: String, // 基础色
    extra_price: Number, // 设计面价格

    is_blank: Boolean, // 是否空白模板

    sku_list: Array, // sku 列表
    color_list: Array, //颜色列表
    size_list: Array, //尺码列表

    select_color: String, //选择的颜色
    select_size: String, //选择的尺码
    sku: String, //商品的sku
    stock: Number, //商品的库存
    weight: Number, //商品的克重kg
    price: Number, // 价格
    tag_price: Number, // 包装袋价格
    pack_price: Number, // 吊牌价格
    quantity: Number, //数量

    tag: Object, // 吊牌
    pack: Object, // 包装
};

// 地址数据类型
const AddressType = {
    id: Number, // 地址id
    first_name: String, // string 姓名
    country_code: String, // string 国家（国际二字码 标准ISO 3166-2 ）
    country: String, // string 国家名称
    city: String, // string 城市
    state: String, // string  州/省
    district: String, // string 区、县（可对应为adress 2）
    street: String, // string 街道/详细地址（可对应为adress 1）
    email: String, // string 邮箱
    phone: String, // string 电话
    post_code: String, // string 邮编
};

// 桉类型格式化值
// opt 要格式化的内容
// type 格式化类型
// dfu 默认值
const getObjectByType = (opt, type, dfu) => {
    let option = opt || {};
    let result = dfu || {};
    Object.keys(type).map((key) => {
        let format = (type && type[key]) || ((v) => v);
        let value = option[key];
        if (typeof value == "undefined") {
            // 为空
            //value不存在时判断result有没有默认值
            result[key] = result[key] || format();
        } else if (result[key] != value) {
            // 值不同
            if (Array.isArray(value)) {
                //判断是否时Array
                result[key] = value;
            } else {
                result[key] = format(value);
            }
        } else {
            // 值相同
        }
    });
    return result;
};

const state = () => ({
    shop_id: 0, // 店铺id
    product: [], //样品订单List
    // 地址信息
    address: {
        tab: "",
        active: 0,
        edit: null,
        list: [],
    },

    // 物流信息
    logistics: {
        iso_code: "",
        weight: 0,
        commodity: 0,
        post_code: "",
        remote_sign: false,
        active: "PK",
        express: [],
    },

    // 折扣
    discount: {
        coupon_loaded: false,
        coupon_active: 0,
        coupon_list: [],
        level_loaded: false,
        level_discount: 100,
        level_num: 1,
    },
});
const getters = {
    getShopId(state) {
        return state.shop_id;
    },
    getLogistics(state) {
        return state.logistics;
    },
    // 获取产品列表
    getProduct(state) {
        return state.product.map((item) => {
            const result = getObjectByType(item, ProductItemType);
            result.user_level = state.discount.level_num;
            result.user_discount = state.discount.level_discount;
            return result;
        });
    },
    // 地址
    getAddress(state) {
        return state.address;
    },
    // 当前地址
    getAddressActive(state) {
        if (state.address.tab == "list") {
            const list = state.address.list;
            const select = list.filter((i) => i.id == state.address.active);
            const active = select[0] || list[0];

            if (active) {
                return getObjectByType(active, AddressType);
            } else {
                return getObjectByType(state.address.edit, AddressType);
            }
        } else {
            return getObjectByType(state.address.edit, AddressType);
        }
    },

    // 折扣信息
    getDiscount(state) {
        // 订单数量
        return state.discount;
    },

    // 计算价格
    getPricing(state) {
        // 商品价格
        // 商品克重
        const discount = state.discount;
        const logistics = state.logistics;
        const result = {
            count: state.product.reduce((p, c) => p + c.quantity, 0), // 数量
            product: 0, // 商品总价
            weight: 0, // 商品重量
            commodity: 0, // 商品总价+折扣后的价格+包装袋价格+吊牌价格+减去空白模板差价

            level_discount: 100, // 用户等级折扣
            level_price: 0, // 用户等级折扣折后价
            level_off: 0, // 用户等级折扣减除的价格
            level_num: 0, // 用户等级

            blank_price: 0, // 空白模板折后价
            blank_off: 0, // 空白模板差价

            tag_original: 0, // 吊牌原价
            tag_price: 0, // 吊牌折后价
            tag_off: 0, // 吊牌价格打折扣除

            pack_original: 0, // 包装袋原价
            pack_price: 0, // 包装袋折后价
            pack_off: 0, // 包装袋打折扣除价格

            coupon_discount: 100, // 优惠劵折扣
            coupon_original: 0, // 商品参与折扣券计算的价格
            coupon_price: 0, // 折扣卷后的价格
            coupon_off: 0, // 使用优惠劵后减除的价格
            coupon_usable: [], // 可用优惠劵
            shipping: 0, // 物流费用
            tax: 0, // 税费

            total: 0, // 最终支付的价格
            remote_sign: logistics.remote_sign,
        };

        const mathRound = (value, n) => {
            n = n === undefined ? 1 : n;
            let bei = Math.pow(10, n);
            let res = Math.round(value * bei) / bei;
            return +parseFloat(res.toPrecision(12));
        };

        // 用户等级折扣
        if (discount.level_discount) {
            result.level_discount = discount.level_discount;
            result.level_num = discount.level_num;
        }

        // 用户选择的优惠劵
        result.coupon_usable = discount.coupon_list.filter((item) => {
            if (item.min_count && item.max_count) {
                return (
                    result.count >= item.min_count &&
                    result.count <= item.max_count
                );
            } else if (item.min_count) {
                return result.count >= item.min_count;
            } else if (item.max_count) {
                return result.count <= item.max_count;
            } else {
                // 兼容旧数据，数量小于等于3的
                return result.count <= 3;
            }
        });
        if (discount.coupon_active) {
            const active = result.coupon_usable.find(
                (item) => item.id == discount.coupon_active
            );

            result.coupon_discount = active ? active.discount_value : 100;
        }

        // 重写啊重写

        // 产品数据
        state.product.map((item) => {
            // 文档地址
            // https://podpartner.feishu.cn/docx/GtBsdaSMRo5CnCxLWD5cMJGQnTd?fromScene=spaceOverview&openbrd=1&doc_app_id=501&blockId=doxcnBE8WbazcGT9CWclAonlu9d&blockType=whiteboard&blockToken=CsrMwjgrohlKGdb3qAscOJKWnwf#doxcnBE8WbazcGT9CWclAonlu9d

            // 数量
            const quantity = parseInt(item.quantity) || 0;
            // 重量
            const weight = parseFloat(item.weight) || 0;
            const price = parseInt(item.price) || 0; // 先计算单价
            const extra = parseInt(item.extra_price) || 0;
            const product = price + extra; // 商品基础价格

            // 核心问题
            // 订单下单时，等级折扣是对所有商品价格的折扣
            // 但是在显示时，要显示每个商品单价中要先算折扣向上取整
            // Math.ceil(price * blank * dis) 和 Math.ceil(Math.ceil(price * blank) * dis) 的区别

            // 01.空白模板折扣后的价格
            // 空白模板差价  计算 5%折扣  向下取整，再累加
            // ！！！！！！这里要进行一次向上取整
            // const blank_discount = item.is_blank ? 0.95 : 1;
            // const product_blank = Math.ceil(product * blank_discount);

            // 商品空白模板之后的价格
            // 向上取整
            const product_blank_price = Math.ceil(
                (item.is_blank ? 0.95 : 1) * product
            );
            const product_blank_off = product - product_blank_price;

            // 02.用户等级折扣后的价格
            const product_level_price = Math.round(
                0.01 * product_blank_price * result.level_discount
            );
            const product_level_off = product_blank_price - product_level_price;

            // 吊牌袋价格
            const tag_original = parseInt(item.tag_price) || 0;
            const tag_level_price = Math.round(
                0.01 * tag_original * result.level_discount
            );
            const tag_level_off = tag_original - tag_level_price;

            // 包装袋价格
            const pack_original = parseInt(item.pack_price) || 0;
            const pack_level_price = Math.round(
                0.01 * pack_original * result.level_discount
            );
            const pack_level_off = pack_original - pack_level_price;

            // 重量
            result.weight += weight * quantity;
            // 商品总的原价
            result.product += product * quantity;

            // 空白模板折扣价
            result.blank_price += product_blank_price * quantity;
            result.blank_off += product_blank_off * quantity;

            // 吊牌价格
            result.tag_original += tag_original * quantity; // 吊牌原价
            result.tag_price += tag_level_price * quantity; // 吊牌原价
            result.tag_off += tag_level_off * quantity; // 吊牌原价

            // 包装袋价格
            result.pack_original += pack_original * quantity; // 包装袋原价
            result.pack_price += pack_level_price * quantity; // 包装袋原价
            result.pack_off += pack_level_off * quantity; // 包装袋原价

            // 用户等级折扣价
            result.level_price +=
                (product_level_price + tag_level_price + pack_level_price) *
                quantity;
            result.level_off +=
                (product_level_off + tag_level_off + pack_level_off) * quantity;

            // 商品参与折扣券计算的价格
            result.coupon_original += product_level_price * quantity;

            // console.log(level_off, tag_off, pack_off);

            // // 商品总价格
            // result.commodity +=
            //     (product_coupon + pack_price + tag_price) * quantity;

            // // 商品折扣价格
            // result.product_discount +=
            //     Math.ceil(
            //         Math.ceil(product * blank_discount) *
            //             0.01 *
            //             result.level_discount
            //     ) * quantity;
        });

        // 接口返回的commodity_prices，表示的总价为
        // 商品的原价+商品设计面加价-商品空白折扣-用户等级折扣-优惠劵折扣
        // 不包括包装和吊牌的价格

        // 优惠劵折扣价
        // 03.优惠折扣后的价格

        result.coupon_price = Math.round(
            0.01 * result.coupon_original * result.coupon_discount
        );
        result.coupon_off = result.coupon_original - result.coupon_price;
        // 税费的总价
        result.commodity = result.coupon_price;

        // 物流价格,税费
        if (logistics.active) {
            const select = logistics.active;
            const active =
                logistics.express.find((item) => item.no == select) || {};

            result.shipping = parseInt(active.price) || 0;
            result.tax = parseInt(active.tax_price) || 0;
        }

        result.total =
            result.tax +
            result.shipping +
            result.coupon_price +
            result.tag_price +
            result.pack_price;

        result.weight = mathRound(result.weight, 2);

        return result;
    },
};
const mutations = {
    // 类型
    SET_SHOP_ID(state, payload) {
        state.shop_id = payload;
    },

    // 设置产品
    SET_PRODUCT(state, payload) {
        state.product = (payload || []).map((item) =>
            getObjectByType(item, ProductItemType)
        );
    },

    // 设置地址
    SET_ADDRESS(state, payload) {
        const option = payload || {};
        state.address = {
            tab: option.tab || "edit",
            active: option.active || 0,
            loaded: false, // 每次初始化都清空
            edit: getObjectByType(option.edit, AddressType),
            list: (option.list || []).map((item) =>
                getObjectByType(item, AddressType)
            ),
        };
    },

    // 订单类型
    SET_ADDRESS_TAB(state, payload) {
        state.address.tab = payload || "edit";
    },

    // 设置选中的id
    SET_ADDRESS_ACTIVE(state, payload) {
        state.address.active = payload || 0;
    },

    // 编辑地址详情
    SET_ADDRESS_EDIT(state, payload) {
        state.address.edit = getObjectByType(payload, AddressType);
    },

    // 设置折扣，刷新页面问题，都认为要重新加载
    SET_DISCOUNT(state, payload) {
        const option = payload || {};
        option.coupon_loaded = false;
        option.level_loaded = false;
        Object.keys(state.discount).map((key) => {
            if (
                Object.prototype.toString.call(option[key]) ==
                "[object Undefined]"
            ) {
                // 为空
            } else {
                state.discount[key] = option[key];
            }
        });
    },

    // 设置物流
    SET_LOGISTICS(state, payload) {
        const option = payload || {};
        Object.keys(state.logistics).map((key) => {
            const type = Object.prototype.toString.call(option[key]);
            if (type == "[object Undefined]") {
                // 为空
            } else {
                state.logistics[key] = option[key];
            }
        });
    },

    // 修改物流
    SET_LOGISTICS_ACTIVE(state, payload) {
        const select = state.logistics.express.filter((i) => i.no == payload);
        if (select.length > 0) {
            state.logistics.active = payload;
        }
    },

    // 修改优惠劵
    SET_COUPON_ACTIVE(state, payload) {
        const select = state.discount.coupon_list.filter(
            (i) => i.id == payload
        );
        if (select.length > 0) {
            state.discount.coupon_active = payload;
        } else {
            state.discount.coupon_active = 0;
        }
    },
};

const actions = {
    // 初始化订单数据
    init(store, payload) {
        const option = payload || {};
        // 要重置优惠劵等信息
        option.address = {
            ...(option.address || {}),
            active: 0,
        };

        option.logistics = {
            ...(option.logistics || {}),
            active: "PK",
            iso_code: "",
            express: [],
        };

        option.discount = {
            ...(option.discount || {}),
            coupon_loaded: false,
            coupon_active: 0,
            coupon_list: [],
            level_loaded: false,
            level_discount: 100,
            level_num: 1,
        };

        // 注意名称可能不一样，很要紧
        option.product = (option.product || []).map((item) => {
            // 默认选中吊牌+包装

            const tag = item.tag || item.tag_design_info;
            const pack = item.pack || item.pack_design_info;
            return {
                ...item,
                tag: tag,
                pack: pack,
                tag_price: parseInt(tag ? tag.total_price : 0),
                pack_price: parseInt(pack ? pack.total_price : 0),
            };
        });

        store.dispatch("initByCache", option);
    },

    initByCache(store, payload) {
        const option = payload || {};
        store.commit("SET_SHOP_ID", option.shop_id || 0);
        store.commit("SET_PRODUCT", option.product || []);
        store.commit("SET_ADDRESS", option.address);
        store.commit("SET_DISCOUNT", option.discount);
        store.commit("SET_LOGISTICS", option.logistics);

        // 立即获取用户等级和优惠劵折扣
        store.dispatch("getDiscountList");
        store.dispatch("getDiscountUser");
    },

    // 地址初始化
    setShippingInit(store, payload) {
        // 样品订单的，才获取列表
        if (store.state.shop_id <= 0) {
            return this.$http("address.search")
                .then((response) => {
                    store.state.address.loaded = true;
                    store.state.address.list = response.data || [];
                    // store.state.address.list = [];
                    return Promise.resolve();
                })
                .catch((error) => {
                    return Promise.reject(error);
                });
        } else {
            return Promise.resolve();
        }
    },

    // 获取物流和税费
    getLogisticsInfo(store) {
        const pricing = store.getters.getPricing;
        const address = store.getters.getAddressActive;

        const commodity =
            pricing.coupon_price + pricing.tag_price + pricing.pack_price;

        // 当前的数据
        const differ = {
            commodity_prices: commodity,
            weight: pricing.weight.toFixed(2),
            iso_code: address.country_code,
            post_code: address.post_code || "",
        };
        // 临时缓存
        const cache = {
            commodity_prices: store.state.logistics.commodity,
            weight: store.state.logistics.weight,
            iso_code: store.state.logistics.iso_code,
            post_code: store.state.logistics.post_code || "",
        };

        if (JSON.stringify(differ) == JSON.stringify(cache)) {
            return Promise.resolve();
        } else {
            return this.$http("Order.getLogisticsInfo", differ)
                .then((result) => {
                    if (result.code === 0) {
                        const list = [];
                        const data = result.data || {};
                        const logistics = store.state.logistics;

                        Object.keys(data).map((key) => {
                            const item = data[key];
                            const no = {
                                pk_shipping: "PK",
                                tk_shipping: "TK",
                                ky_shipping: "KY",
                            };
                            const name = {
                                pk_shipping: "Standard",
                                ky_shipping: "Fast",
                                tk_shipping: "Express",
                            };

                            if (item.is_open) {
                                item.tax_price = data.tax_price;
                                item.name = name[key];
                                item.no = no[key];
                                list.push(item);
                            }
                        });

                        // 选中的
                        const select =
                            list.filter((i) => i.no == logistics.active)[0] ||
                            list[0];

                        logistics.active = (select || {}).no || "PK";
                        logistics.express = list;
                        logistics.remote_sign = data.remote_sign;
                        logistics.commodity = differ.commodity_prices;
                        logistics.weight = differ.weight;
                        logistics.iso_code = differ.iso_code;
                        logistics.post_code = differ.post_code;

                        return Promise.resolve();
                    } else {
                        const logistics = store.state.logistics;
                        logistics.active = "";
                        logistics.express = [];
                        logistics.remote_sign = false;
                        logistics.commodity = 0;
                        logistics.weight = 0;
                        logistics.iso_code = "";
                        logistics.post_code = "";
                        return Promise.reject(result);
                    }
                })
                .catch((error) => {
                    const logistics = store.state.logistics;
                    logistics.active = "";
                    logistics.express = [];
                    logistics.remote_sign = false;
                    logistics.commodity = 0;
                    logistics.weight = 0;
                    logistics.iso_code = "";
                    logistics.post_code = "";
                    return Promise.reject(error);
                });
        }
    },

    // 优惠卷清单
    getDiscountList(store) {
        let sample = store.state.shop_id <= 0;

        if (store.state.discount.coupon_loaded) {
            // 已经获取了
            return Promise.resolve();
        } else if (sample) {
            // 优惠券
            return this.$http("Discount.getDiscount")
                .then((response) => {
                    const list = (response.data || []).map((item) => {
                        item.min_count = parseInt(item.min_count) || 0;
                        item.max_count = parseInt(item.max_count) || 0;

                        // 兼容旧数据，原优惠劵只支持3件以内的
                        if (!item.min_count && !item.max_count) {
                            item.max_count = 3;
                            item.min_count = 0;
                        }
                        return item;
                    });

                    store.state.discount.coupon_active = 0;
                    store.state.discount.coupon_list = list;
                    store.state.discount.coupon_loaded = true;
                    return Promise.resolve();
                })
                .catch((error) => {
                    return Promise.reject(error);
                });
        } else {
            store.state.discount.coupon_loaded = true;
            return Promise.resolve();
        }
    },

    // 用户等级优惠
    getDiscountUser(store) {
        // 优惠券
        if (store.state.discount.level_loaded) {
            // 已经获取了
            return Promise.resolve();
        } else {
            return this.$http("User.dashBoard")
                .then((response) => {
                    if (response.code == 0) {
                        let discount = 1; // 等级折扣比例
                        let data = response.data || {};
                        let salesLevel = parseInt(data.level) || 1;
                        let discountList = JSON.parse(data.show_label || "[]");
                        discountList.map((item, index) => {
                            // 等级从2开始
                            let level = index + 2;
                            if (salesLevel >= level) {
                                discount = item.discount;
                            }
                        });

                        store.state.discount.level_discount = discount * 100;
                        store.state.discount.level_num = salesLevel;
                        store.state.discount.level_loaded = true;

                        // store.state.discount.level_discount = 100;
                        // store.state.discount.level_num = 1;

                        return Promise.resolve();
                    } else {
                        store.state.discount.level_discount = 100;
                        store.state.discount.level_num = 1;
                        store.state.discount.level_loaded = true;
                        return Promise.resolve();
                    }
                })
                .catch((error) => {
                    store.state.discount.level_discount = 100;
                    store.state.discount.level_num = 1;
                    store.state.discount.level_loaded = true;
                    return Promise.reject(error);
                });
        }
    },

    // 确认订单
    setConfirmInit(store, payload) {
        // 获取产品重量
        // 获取物流地址
        // 如果有改变，就重新取数据
        return Promise.all([
            store.dispatch("getDiscountList"),
            store.dispatch("getDiscountUser"),
        ]).then((result) => {
            return store.dispatch("getLogisticsInfo");
        });
    },
};
export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions,
};
